<template>
  <Box :title="detailTitle" class="event-related-detail" direction="row" >
    <!-- 摄像机  -->
    <div class="layout detail-left">
      <Panel class="camera-switch" second :title="cameraList[0] && cameraList[0].name" align="center">
        <VideoPlayer :url="cameraList[0] && cameraList[0].url"></VideoPlayer>
      </Panel>
      <Panel class="camera-switch" second :title="cameraList[1] && cameraList[1].name" align="center">
        <VideoPlayer :url="cameraList[1] && cameraList[1].url"></VideoPlayer>
      </Panel>
    </div>
    <div class="layout detail-center">
      <div class="top">
        <!-- 情报板 -->
        <Panel class="camera-switch" second title="" align="center">
          <Switch :list="qbbList" renderType="qbb"></Switch>
          <Empty v-if="!qbbList.length" emptyData="暂无情报板数据 " />
        </Panel>
        <!-- 附近事件 -->
        <Round :roundEvent="roundEvent" :roundGuest="roundGuest" class="near-event"></Round>
      </div>

      <div class="bottom">
        <!-- 拥堵路段断面平均车速统计 -->
        <Panel class="line-chart" second>
          <LineChart :seriesData="seriesData" :title="title" :xDate="xDate" />
        </Panel>
        <!-- 即时通讯 -->
        <!-- <Panel class="im" second>
          <div class="information-list scroll-hover">
            <div class="message left" v-for="i in 15" :key="i.id">
              <span class="time">13:51</span><span class="describe">我遇到麻烦了</span>
            </div>
            <div class="message right">
              <span class="time">13:51</span><span class="describe">请问有什么能帮您?</span>
            </div>
          </div>
          <div class="send-information">
            <div class="icon"><span></span></div>
            <div class="send">
              <a-input class="ipt" placeholder="请输入" />
              <div class="send-icon"></div>
            </div>
          </div>
        </Panel> -->
      </div>
    </div>

    <a-spin class="spin-loading" v-show="spinning" />
  </Box>
</template>

<script>
export default {
  name: 'EventRelatedDetail'
}
</script>
<script setup>
/**
 * 事件相关详情(三级)
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2022/10/24
 */

import Box from '../../components/detail/Box.vue'
import LineChart from '../../components/charts/ShadowLine.vue'
import Switch from '../../components/detail/Switch.vue'
import Round from '../../components/detail/Round.vue'
import Empty from '../../components/empty'
import trafficApi from '../../api/traffic'
import eventApi from '../../api/event'
import baseServiceApi from '../../api/base-service'
import { ref, defineProps, watch, getCurrentInstance, computed } from 'vue'
import useMapOperates from '@/hooks/useMapOperates'
import dayjs from 'dayjs'
import { useStore } from 'vuex'
import useComputedDistanceRow from '@/hooks/useComputedDistanceRow'
import Panel from '../../components/panel'
import VideoPlayer from '@/components/video-player/VideoPlayer.vue'

const props = defineProps({
  // 数据项
  data: {
    type: Object,
    default: () => {}
  }
})

const { proxy } = getCurrentInstance()
// 点位、弹框的处理
const handleDark = useMapOperates()
const store = useStore()
// loading
const spinning = ref(false)
// 详情标题
const detailTitle = ref('')

const orgId = computed(() => (store.state.user.userInfo.orgInfos ? store.state.user.userInfo.orgInfos[0].orgId : ''))

// 摄像机列表
const cameraList = ref([])
// 情报板列表
const qbbList = ref([])
const roadType = computed(() => store.state.config.roadType)

// 折线图数据
const title = '事件断面平均车速' // 拥堵路段断面平均车速
const xDate = ref([])
const seriesData = ref([
  {
    gradientColor: [
      { offset: 0, color: 'rgb(158, 205, 245)' },
      { offset: 1, color: 'rgb(210, 229, 251)' }
    ],
    color: '#16ade1',
    markLine: {
      lineStyle: {
        type: 'solid',
        color: 'red',
        width: 3
      },
      label: {
        show: false
      },
      symbol: false,
      data: [
        {
          xAxis: ''
        }
      ]
    },
    data: []
  }
])

const roundEvent = ref({
  accident: 0,
  construction: 0
}) // 附近事件
const roundGuest = ref({}) // 附近两客一危

const eventIcon = {
  TAB1: 'jtsg', // '交通事故'
  TAB2: 'clgz', // '车辆故障'
  JEB1: 'sgyh', // '施工养护'
  TBB1: 'eltq', // '恶劣天气'
  TDB2: 'zaw', // '障碍物'
  TDB1: 'dll', // '大流量'
  JGB1: 'jtgz'
}

/**
 * 获取数据
 */
const getData = () => {
  // 获取事件时间

  const mm = dayjs(props.data.happenTime).minute()
  const eventDate =
    mm % 2 == 0
      ? dayjs(props.data.happenTime).format('HH:mm')
      : dayjs(props.data.happenTime)
          .minute(mm - 1)
          .format('HH:mm')
  console.log('eventDate', eventDate)
  // console.log(props.data)

  // spinning.value = true
  detailTitle.value = props.data.describe
  drawLayer(props.data)

  // 情报版详情
  // baseServiceApi
  //   .getInformationDetail({
  //     informationId: 'K219+500_CMS',
  //     roadType: roadType.value
  //   })
  //   .then(res => {
  //     qbbList.value = res.data || []
  //   })
  const params = {
    roadCode: props.data.roadId, // 道路编码，如：S87
    roadType: roadType.value, // 道路类型，普通公路：2，高速公路：1
    eventTime: props.data.happenTime ? dayjs(props.data.happenTime).format('YYYYMMDDHHMM') : null, // 事件时间，格式：yyyyMMddHHmm 例如：202207071028.
    upAndDown: props.data.upAndDown // 行驶方向，如：1
  }
  // 断面车速
  trafficApi.getSpeedFlow(params).then(res => {
    const data = res.data
    console.log('断面车速', res.data)
    if (data) {
      seriesData.value[0].data = data.value || []
      seriesData.value[0].markLine.data[0].xAxis = eventDate
      xDate.value = data.dateList || []
    }
  })
  // .finally(() => {
  //   setTimeout(() => {
  //     spinning.value = false
  //   }, 1000)
  // })

  // 附近事件、附近两客一危
  // baseServiceApi.getRangeGuest({}).then(res => {
  //   const data = res.data || {}
  //   roundGuest.value.whc = data.dangerousArticles
  //   roundGuest.value.kc = (data.motorBus || 0) + (data.microBus || 0)
  // })
}

/**
 * 地图图层操作
 */
const drawLayer = data => {
  const path = data.heatModelList.map(item => [item.lon, item.lat])
  props.data.eventType === 'JGB1' && getDkLonLat()

  const centerPath = path[Math.floor(path.length / 2)]
  if (!centerPath[0] || !centerPath[1]) return
  // 施工画线、周边摄像机
  if (['JEB1'].includes(data.eventType)) {
    const startStake = data.startStake.replace(new RegExp('K'), '').split('+').join('.')
    const endStake = data.endStake.replace(new RegExp('K'), '').split('+').join('.')

    const params = {
      roadNum: data.roadId, //  string 是 示例值：G2说明：路段编号
      startStake: startStake, //  number 是 示例值：450说明：开始桩号
      endStake: endStake //  number 是 示例值：1000说明：结束桩号
    }
    // 获取路线
    getLineLatLonList({ text: '施工', lineColor: '#fcb42d' }, params)
    // 获取摄像机
    params.resourceType = 6
    getBaseInfoList(params, 'sxj', centerPath)
    // params.resourceType = 7
    // getBaseInfoList(params, 'qbb', centerPath)
  } else {
    // 获取摄像机
    baseServiceApi.getLonlatInfoList({ lon: centerPath[0], lat: centerPath[1], resourceType: 6 }).then(async res => {
      if (res.data && res.data.length) {
        let result = res.data.filter(i => i.roadSysType === 1) // 只要高速的
        result = useComputedDistanceRow(centerPath, result).splice(0, 2)
        result = result.map(item => {
          return {
            ...item,
            id: item.resourcesId,
            cameraId: item.resourcesId,
            roadType: item.roadSysType,
            icon: 'zhdd-gs-sxj-active',
            path: [item.lng, item.lat],
            name: item.resourcesName,
            hasClickStatus: true,
            size: [30, 35],
            offset: [-15, -35]
          }
        })
        console.warn(result)
        cameraList.value = await getCameraUrls(result)
        console.log('cameraList.value ', cameraList.value)

        handleDark('marker', cameraList.value)
      }
    })
  }

  // handleDark(
  //   'marker',
  //   [
  //     {
  //       icon: 'zhdd-gl-sxj',
  //       path: [Number(centerPath[0]) - 0.03, Number(centerPath[1]) - 0.03],
  //       name: '摄像头',
  //       size: [30, 35],
  //       offset: [-15, -35],
  //       hasClickStatus: true
  //     }
  //   ],
  //   { type: 'sxj' }
  // )
  // handleDark(
  //   'marker',
  //   [
  //     {
  //       icon: 'zhdd-gl-qbb',
  //       path: [Number(centerPath[0]) + 0.03, Number(centerPath[1]) + 0.03],
  //       name: '情报板',
  //       hasClickStatus: true,
  //       size: [30, 35],
  //       offset: [-15, -35]
  //     }
  //   ],
  //   { type: 'qbb' }
  // )

  // 打点
  // if (['AA', 'BA', 'CA', 'DA'].includes(data.eventType)) {
  handleDark(
    'marker',
    [
      {
        ...data,
        icon: 'zhdd-gs-' + eventIcon[data.eventType],
        path: centerPath,
        name: data.describe,
        zIndex: 105,
        hasClickStatus: true,
        eventType: data.eventType,
        size: [30, 35],
        offset: [-15, -35]
      }
    ],
    {
      type: 'dlsj'
    }
  )
  // } else {
  //   // 画线
  //   handleDark('polyline', dataArr)
  // }
  const circle = new AMap.Circle({
    center: new AMap.LngLat(centerPath[0], centerPath[1]), // 圆心位置
    radius: 5000 // 半径 单位m
  })

  const bounds = circle.getBounds()
  const imageData = {
    url: require('../../assets/images/event/red-scope.png'),
    southWest: [bounds.southwest.lng, bounds.southwest.lat],
    northEast: [bounds.northeast.lng, bounds.northeast.lat]
  }
  const config = {
    zooms: [8, 14],
    zIndex: 2
  }
  handleDark('image', imageData, config)
  proxy.$mapSdk().setMvMapCenterAndZoom([Number(centerPath[0]), Number(centerPath[1]) - 0.03], 13)
}

/** *
 * @desc  获取路线
 * @param params  请求参数
 *
 ***/
function getLineLatLonList(newValue = {}, params) {
  proxy
    .$mapSdk()
    .getLineLatLonList(newValue, params)
    .then(res => {
      if (res && res.length) handleDark('polyline', res)
    })
}

/** *
 * @desc  获取摄像机、情报板并打点
 * @param params  请求参数
 * @param type    类型  sxj摄像机、qbb情报板
 *
 ***/
function getBaseInfoList(params, type = '', path) {
  proxy
    .$mapSdk()
    .getBaseInfoList(params, type)
    .then(async res => {
      const result = useComputedDistanceRow(path, res)
      if (type == 'sxj') {
        const beforeVideo = result.splice(0, 2)
        beforeVideo[0].icon = beforeVideo[1].icon = 'zhdd-gs-sxj-active'
        cameraList.value = await getCameraUrls(beforeVideo)

        handleDark('marker', beforeVideo)
        // handleDark('marker', result, { type })
      } else {
        handleDark('marker', res, { type })
      }
    })
}

/**
 * @desc 获取附近的高速摄像机url地址
 *
 * **/
function getCameraUrls(list) {
  return new Promise((resolve, reject) => {
    const promiseList = list.map(i => {
      return baseServiceApi.getCameraUrl({
        roadType: 1,
        cameraId: i.resourcesId,
        videoType: 1
      })
    })
    Promise.allSettled(promiseList)
      .then(result => {
        result.forEach((item, index) => {
          console.log('item', item)

          if (item.status === 'fulfilled' && item.value.code == 200 && item.value.detail) {
            // cameraList.value[index].url = item.detail
            list[index].url = item.value.detail
          }
        })
        resolve(list)
      })
      .catch(() => reject([]))
  })
}

/**
 * 监听id变化
 */
watch(
  () => props.data.eventId,
  (newVal, oldVal) => {
    getData()
  },
  { deep: true, immediate: true }
)
/**
 * 获取道口经纬度并打点
 *
 * **/
function getDkLonLat() {
  const params = {
    province: 32,
    unitId: props.data.orgId,
    eventId: props.data.eventId,
    rcId: props.data.sectioncenterid
  }
  eventApi.getCoordinateAbouts(params).then(res => {
    const stationMarkers = (res.data || []).map(i => {
      return {
        ...i,
        name: i.stationname,
        path: [i.lon, i.lat],
        tsname: i.stationname.split('(')[0],
        eventType: 'JGB1',
        icon: 'zhdd-gs-jtgz'
      }
    })
    console.log('stationMarkers', stationMarkers)
    if (stationMarkers.length) {
      getMarkerSxj(stationMarkers[0].path)
      proxy.$mapSdk().setMapCenter(stationMarkers[0].path)
    }
    handleDark('marker', stationMarkers, { type: 'dlsj' })
  })
}
/**
 * 交通管制点位附近摄像机
 * **/
function getMarkerSxj(path) {
  if (!Array.isArray(path)) return
  // const _path = path // || [[120.62173935320476, 31.348696499246007]]
  baseServiceApi
    .getLonlatInfoList({ lon: path[0], lat: path[1], resourceType: 6 })
    .then(async res => {
      if (res.data && res.data.length) {
        let result = res.data.filter(i => i.roadSysType === 1) // 只要高速的
        result = useComputedDistanceRow(path, result).splice(0, 2)
        result = result.map(item => {
          return {
            ...item,
            id: item.resourcesId,
            cameraId: item.resourcesId,
            roadType: item.roadSysType,
            icon: 'zhdd-gs-sxj-active',
            path: [item.lng, item.lat],
            name: item.resourcesName,
            hasClickStatus: true,
            size: [30, 35],
            offset: [-15, -35]
          }
        })

        cameraList.value = await getCameraUrls(result)
        console.log('cameraList.value ', cameraList.value)
        handleDark('marker', cameraList.value)
      }
    })
    .catch(e => {
      console.log('getMarkerSxj err', e)
      cameraList.value = []
    })
}
</script>

<style scoped lang="less">
@import url(../../styles/themes/index.less);

.event-related-detail {
  .detail-box-content {
    justify-content: space-between;

    .mz-panel {
      margin-right: 0;
    }

    .layout {
      display: flex;
      flex-direction: column;
      height: 100%;
      justify-content: space-between;
    }

    .detail-left {
      width: 30%;

      .camera-switch {
        height: 49%;
      }
    }

    .detail-center {
      flex: 1;
      margin-left: 10px;

      .top,
      .bottom {
        height: 49%;
        display: flex;
        .camera-switch,
        .line-chart {
          flex: 1;
        }
        .near-event,
        .im {
          margin-left: 10px;
          width: 330px;
        }
      }
    }

    .detail-right {
      width: 30%;

      .near-event {
        width: 100%;
        height: 49%;
      }

      .im {
        height: 49%;
        display: flex;
        flex-direction: column;

        .information-list {
          flex: 1;

          .message {
            display: flex;
            flex-direction: column;
            font-size: 14px;
            font-family: Source Han Sans CN, Source Han Sans CN-Regular;
            font-weight: 400;
            color: #333333;
            letter-spacing: 0.35px;
            line-height: 18px;
            margin-bottom: 10px;
            word-wrap: break-word;
            word-break: break-all;

            &.left {
              align-items: flex-start;
              margin-right: 40%;

              .describe {
                background: #ffffff;
              }
            }

            &.right {
              align-items: flex-end;
              margin-left: 40%;
              padding-right: 5px;

              .describe {
                background: #cfddf7;
              }
            }

            .time {
              font-size: 12px;
              font-weight: 400;
              color: #333333;
              letter-spacing: 0.3px;
              margin-bottom: 5px;
            }

            .describe {
              font-size: 14px;
              border-radius: 4px;
              line-height: 24px;
              padding: 2px 8px 2px 10px;
              word-wrap: break-word;
              word-break: break-all;
            }
          }
        }

        .send-information {
          width: 100%;
          display: flex;
          height: 30px;
          margin: 5px 0;

          .icon {
            width: 30px;
            background: #ffffff;
            border: 1px solid #c6d4ef;
            border-radius: 2px;
            margin-right: 5px;
            display: flex;
            align-items: center;
            justify-content: center;

            span {
              width: 16px;
              height: 14px;
              background: url(../../assets/images/event/information.png);
              background-size: 100% 100%;
            }
          }

          .send {
            position: relative;
            flex: 1;

            .ipt {
              width: 100%;
              height: 100%;
              border: 1px solid #83a3e2b8;
              padding-left: 10px;
            }

            .send-icon {
              width: 16px;
              height: 14px;
              position: absolute;
              right: 10px;
              top: 30%;
              cursor: pointer;
              background: url(../../assets/images/event/send.png);
              background-size: 100% 100%;
            }
          }
        }
      }
    }
  }
}
</style>
